/**
 *
 * @author Jeison Hernandez
 * @date 06/03/2011
 *
 */
package ellipse;

import processing.core.*;

public class Main extends PApplet {

    /**
     * Creación de variables globales para el programa
     *
     **/
    int xStart, yStart, xEnd, yEnd;

    public static void main(String[] args) {
        PApplet.main(new String[]{"ellipse.Main"});
    }

    @Override
    public void setup() {
        size(800, 600);
        background(30, 75, 143);
        stroke(255);
    }

    @Override
    public void draw() {
    }

    @Override
    public void mousePressed() {
        xStart = mouseX;
        yStart = mouseY;
    }

    @Override
    public void mouseDragged() {
        int xParameter, yParameter, xMax, xMin, yMax, yMin, a, b;
        background(30, 75, 143);
        xEnd = mouseX;
        yEnd = mouseY;
        if(xEnd>xStart){
        xMax=xEnd;
        xMin=xStart;
        }else{
        xMax=xStart;
        xMin=xEnd;
        }
        if(yEnd>yStart){
        yMax=yEnd;
        yMin=yStart;
        }else{
        yMax=yStart;
        yMin=yEnd;
        }
        xParameter= ((xMax-xMin)/2)+xMin;
        yParameter= ((yMax-yMin)/2)+yMin;
        midpointEllipse(xParameter, yParameter, (int)((xMax-xMin)/2), (int)((yMax-yMin)/2));
    }

    public void simetry(int x, int y, int xStart, int yStart) {
        point(x + xStart, y + yStart);
        point((-x) + xStart, y + yStart);
        point((-x) + xStart, (-y) + yStart);
        point(x + xStart, (-y) + yStart);


    }

    public void midpointEllipse(int xStart, int yStart, int a, int b) {
        int x = 0, y = b;
        double d1 = (b * b) - (a * a * b) + ((a * a) / 4);
        double d2;
        simetry(x, y, xStart,yStart);

        while (((a * a) * (y - 0.5)) > ((b * b) * (x + 1))) {
            if (d1 < 0) {
                d1 = d1 + ((b * b) * (2 * x + 3));
                x++;
                simetry(x, y,xStart,yStart);
            } else {
                d1 = d1 + ((b * b) * (2 * x + 3)) + ((a * a) * (-2 * y + 2));
                x++;
                y--;
                simetry(x, y, xStart, yStart);
            }
        }


        while (y>0) {
            if (d1 < 0) {
                d1 = d1 + b*b * (2*x + 2) + a*a * (-2*y + 3);
                x++;
                y--;
                simetry(x, y, xStart, yStart);
            } else {
                d1 = d1 +a*a * (-2*y + 3);
                y--;
            }
            simetry(x, y, xStart, yStart);
        }

    }
}
